/* eslint-disable no-param-reassign */
/* eslint-disable no-mixed-operators */
/* eslint-disable max-classes-per-file */
/* eslint-disable no-plusplus */
/* eslint-disable comma-dangle */

import html2canvas from 'html2canvas';
import Animation from './animation';

const isMobile = window.pageParams && window.pageParams.mobile;

function createCanvas() {
  const bg = document.createElement('div');
  const canvas = document.createElement('canvas');
  const title = document.createElement('p');
  const subtitle = document.createElement('a');

  title.innerText = '愚人节快乐！';
  title.style.textAlign = 'center';
  title.style.fontSize = '64px';
  subtitle.innerHTML = `推广：点此链接免费注册码云企业版`;
  subtitle.href = 'https://gitee.com/enterprises/new?from=gitee.com';
  subtitle.style.color = 'red';
  bg.style.textAlign = 'center';
  bg.style.display = 'flex';
  bg.style.flexDirection = 'column';
  bg.style.justifyContent = 'center';
  bg.style.alignItems = 'center';
  bg.style.backgroundColor = '#fff';
  bg.style.position = 'fixed';
  bg.style.left = 0;
  bg.style.top = 0;
  bg.style.width = '100%';
  bg.style.height = '100%';
  bg.style.zIndex = 10000;
  canvas.style.pointerEvents = 'none';
  canvas.style.position = 'fixed';
  canvas.style.left = 0;
  canvas.style.top = 0;
  canvas.style.width = '100%';
  canvas.style.height = '100%';
  canvas.style.zIndex = 10001;
  if (isMobile) {
    canvas.width = window.innerWidth;
  } else {
    canvas.width = Math.max(1040, window.innerWidth);
  }
  canvas.height = window.innerHeight;
  bg.appendChild(title);
  bg.appendChild(subtitle);
  document.body.appendChild(bg);
  document.body.appendChild(canvas);
  document.body.style.overflow = 'hidden';
  bg.addEventListener('click', (e) => {
    bg.parentNode.removeChild(bg);
    canvas.parentNode.removeChild(canvas);
    document.body.style.overflow = 'auto';
  });
  return canvas;
}

function playAnimation() {
  document.body.style.overflow = 'hidden';
  html2canvas(document.body).then((bodyCanvas) => {
    const image = new Image();

    image.onload = () => {
      new Animation(image, createCanvas(), window.innerWidth / bodyCanvas.width).render();
    }
    image.src = bodyCanvas.toDataURL('image/png');
  });
}

function waitProjectReadmeLoaded() {
  // 等待仓库的 README 内容加载完成
  if (document.querySelector('.readme-box')) {
    playAnimation();
    return;
  }
  setTimeout(waitProjectReadmeLoaded, 1000);
}

window.addEventListener('load', () => {
  const image = new Image();
  const { hostname } = window.location;

  if (hostname === 'localhost' || hostname.endsWith('.gitee.io')) {
    image.onload = () => { new Animation(image, createCanvas()).render(); };
    image.src = 'image.png';
    return;
  }
  if (hostname === 'gitee.com') {
    if (new Date() > new Date('2020-04-03 00:00:00')
      || window.location.pathname !== '/gitee-frontend/page-animation') {
      return;
    }
  }
  if (isMobile) {
    waitProjectReadmeLoaded()
  } else {
    playAnimation();
  }
});
